import React, {memo} from 'react'
import {shallowEqual, useDispatch, useSelector} from "react-redux";
import {addNumberAction, changeMessageAction, subNumberAction} from "./store/modules/counter";


const Home = memo(() => {

    const {message} = useSelector((state) => ({
        message: state.counterReducerStore.message
    }),shallowEqual);

    const dispatch = useDispatch();

    function changeMessageHandler(num) {
        dispatch(changeMessageAction(num))
    }

    console.log("render Home")
    return <div><h2>Home message:{message}</h2>
        <button onClick={() => changeMessageHandler('你好message')}> message</button>
    </div>
})


const AppHooks = memo(() => {

// 1.使用useSelector将redux中store的数据映射到组件内
    const {count} = useSelector((state) => ({
        count: state.counterReducerStore.count
    }),shallowEqual)

    // 2.使用dispatch直接派发action
    const dispatch = useDispatch()

    function numberHandler(num, isAdd = true) {
        if (isAdd) {
            dispatch(addNumberAction(num))
        } else {
            dispatch(subNumberAction(num))
        }
    }
    console.log("render AppHooks")
    return (
        <div>
            <h2>当前计数:{count}</h2>
            <button onClick={() => numberHandler(1)}>+1</button>
            <button onClick={() => numberHandler(1, false)}>-1</button>
            <Home/>
        </div>
    )
})


export default AppHooks